<template>
  <div class="dashboard">
    <!-- 加载状态 -->
    <el-loading v-if="loading" :fullscreen="true" />

    <el-row :gutter="20">
      <!-- 统计卡片 -->
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <div class="stat-icon identity">
              <el-icon><User /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ stats.identityCount }}</div>
              <div class="stat-label">身份信息</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <div class="stat-icon income">
              <el-icon><Money /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ stats.incomeCount }}</div>
              <div class="stat-label">收入信息</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <div class="stat-icon platform">
              <el-icon><OfficeBuilding /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ stats.platformCount }}</div>
              <div class="stat-label">平台信息</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <div class="stat-icon users">
              <el-icon><Avatar /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ stats.userCount }}</div>
              <div class="stat-label">系统用户</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <!-- 最近活动 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>最近活动</span>
              <el-button type="primary" size="small" @click="loadRecentActivities">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
            </div>
          </template>

          <div v-if="recentActivities.length > 0">
            <el-timeline>
              <el-timeline-item
                  v-for="activity in recentActivities"
                  :key="activity.id"
                  :timestamp="activity.time"
                  :type="activity.type">
                {{ activity.content }}
              </el-timeline-item>
            </el-timeline>
          </div>

          <div v-else style="text-align: center; padding: 40px;">
            <el-empty description="暂无活动记录" />
          </div>
        </el-card>
      </el-col>

      <!-- 快速操作 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>快速操作</span>
            </div>
          </template>
          <div class="quick-actions">
            <el-button
                type="primary"
                size="large"
                @click="$router.push('/upload')"
                style="margin: 10px;">
              <el-icon><Upload /></el-icon>
              数据导入
            </el-button>

            <el-button
                type="success"
                size="large"
                @click="$router.push('/report')"
                style="margin: 10px;">
              <el-icon><Document /></el-icon>
              税务报送
            </el-button>

            <el-button
                type="primary"
                size="large"
                @click="$router.push('/tax-management')"
                style="margin: 10px;">
              <el-icon><DataAnalysis /></el-icon>
              税务数据管理
            </el-button>

            <el-button
                type="warning"
                size="large"
                @click="$router.push('/logs')"
                style="margin: 10px;">
              <el-icon><List /></el-icon>
              系统日志
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <!-- 系统信息 -->
      <el-col :span="24">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>系统信息</span>
              <el-button type="primary" size="small" @click="refreshAllData">
                <el-icon><Refresh /></el-icon>
                刷新数据
              </el-button>
            </div>
          </template>
          <el-descriptions :column="3" border>
            <el-descriptions-item label="系统名称">涉税信息报送系统</el-descriptions-item>
            <el-descriptions-item label="当前用户">{{ userStore.userInfo?.realName || userStore.userInfo?.username || '未知' }}</el-descriptions-item>
            <el-descriptions-item label="用户角色">{{ getRoleLabel(userStore.userInfo?.role) }}</el-descriptions-item>
            <el-descriptions-item label="系统版本">v1.0.0</el-descriptions-item>
            <el-descriptions-item label="系统状态">
              <el-tag type="success">正常运行</el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useUserStore } from '../stores/user'
import { dashboardApi } from '../api'
import { ElMessage, ElLoading } from 'element-plus'
import {
  Money,
  User,
  OfficeBuilding,
  Avatar,
  Upload,
  Document,
  List,
  Setting,
  UserFilled,
  Lock,
  Menu,
  Refresh,
  Key,
  DataAnalysis
} from '@element-plus/icons-vue'

const userStore = useUserStore()

const stats = ref({
  incomeCount: 0,
  identityCount: 0,
  platformCount: 0,
  userCount: 0
})

const recentActivities = ref([])
const lastLoginTime = ref('')
const loading = ref(false)

const getRoleLabel = (role) => {
  if (!role) return '未知'
  const labels = {
    'ADMIN': '管理员',
    'USER': '普通用户'
  }
  return labels[role] || role
}

const loadStats = async () => {
  try {
    loading.value = true
    const response = await dashboardApi.getStats()
    if (response.data.code === 200) {
      const data = response.data.data
      stats.value = {
        incomeCount: data.incomeCount || 0,
        identityCount: data.identityCount || 0,
        platformCount: data.platformCount || 0,
        userCount: data.userCount || 0
      }
    } else {
      ElMessage.warning('获取统计数据失败，使用默认值')
      setDefaultStats()
    }
  } catch (error) {
    console.error('加载统计数据失败:', error)
    ElMessage.error('获取统计数据失败，使用默认值')
    setDefaultStats()
  } finally {
    loading.value = false
  }
}

const setDefaultStats = () => {
  stats.value = {
    incomeCount: 0,
    identityCount: 0,
    platformCount: 0,
    userCount: 0
  }
}

const loadRecentActivities = async () => {
  try {
    const response = await dashboardApi.getRecentActivities()
    if (response.data.code === 200) {
      recentActivities.value = response.data.data || []
    } else {
      ElMessage.warning('获取最近活动失败，使用默认数据')
      setDefaultActivities()
    }
  } catch (error) {
    console.error('加载最近活动失败:', error)
    ElMessage.error('获取最近活动失败，使用默认数据')
    setDefaultActivities()
  }
}

const setDefaultActivities = () => {
  recentActivities.value = [
    {
      id: 1,
      content: '系统初始化完成',
      time: new Date().toLocaleString(),
      type: 'info'
    }
  ]
}

const loadSystemInfo = async () => {
  try {
    const response = await dashboardApi.getSystemInfo()
    if (response.data.code === 200) {
      const data = response.data.data
      lastLoginTime.value = data.lastLoginTime || new Date().toLocaleString()
    } else {
      lastLoginTime.value = new Date().toLocaleString()
    }
  } catch (error) {
    console.error('获取系统信息失败:', error)
    lastLoginTime.value = new Date().toLocaleString()
  }
}

const refreshAllData = async () => {
  loading.value = true
  try {
    await Promise.all([
      loadStats(),
      loadRecentActivities(),
      loadSystemInfo()
    ])
    ElMessage.success('数据刷新成功！')
  } catch (error) {
    console.error('刷新数据失败:', error)
    ElMessage.error('数据刷新失败！')
  } finally {
    loading.value = false
  }
}

onMounted(async () => {
  await Promise.all([
    loadStats(),
    loadRecentActivities(),
    loadSystemInfo()
  ])
})
</script>

<style scoped>
.dashboard {
  padding: 20px;
}

.stat-card {
  height: 120px;
}

.stat-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  font-size: 24px;
  color: white;
}

.stat-icon.income {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon.identity {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-icon.platform {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-icon.users {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.quick-actions {
  text-align: center;
}

.quick-actions .el-button {
  width: 120px;
}
</style>
